import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/login/LoginPage.vue') },
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/scenicarea/manage',
      children: [
        {
          path: '/scenicspot/manage',
          component: () => import('@/views/scenicspot/ScenicSpotManage.vue')
        },
        {
          path: '/tag/manage',
          component: () => import('@/views/tag/TagManage.vue')
        },
        {
          path: '/user/profile',
          component: () => import('@/views/user/UserProfile.vue')
        },
        {
          path: '/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue')
        },
        {
          path: '/user/password',
          component: () => import('@/views/user/UserPassword.vue')
        },
        {
          path: '/line/manage',
          component: () => import('@/views/line/LineManage.vue')
        },
        {
          path: '/scenicarea/manage',
          component: () => import('@/views/scenicarea/ScenicAreaManage.vue')
        },
        {
          path: '/city/manage',
          component: () => import('@/views/city/CityManage.vue')
        }
      ]
    },

    { path: '/test', component: () => import('@/views/test/test11.vue') }
  ]
})

router.beforeEach((to, from, next) => {
  const useStore = useUserStore()

  // 如果没有token, 且访问的是非登录页，拦截到登录
  if (!useStore.token && to.path !== '/login') {
    return next('/login')
  }

  // 如果是首次进入应用且路径为根路径，重定向到 /login
  if (to.path === '/' && from.path === '') {
    return next('/login')
  }

  next()
})

export default router
